package com.westvalley.syn.service;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.kit.LogKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.westvalley.common.kit.StringKit;
import com.westvalley.syn.address.prop.AddressProp;
import com.westvalley.syn.bean.Result;
import com.westvalley.syn.bean.SynResult;
import com.westvalley.http.HttpXmlClient;

/**
 * 同步抽象类
 * @author mos
 *
 */
public abstract class SynService {
	protected AddressProp prop = AddressProp.me();
	protected String url;
	
	/**
	 * 初始化接口传入参数
	 * @param params
	 */
	protected void initParams(Map<String,String> params){
	}
	
	/**
	 * 执行接口
	 * @param params
	 * @return
	 */
	protected Object executeInterface(Map<String,String> params){
		//params.put("appId", prop.getPropValue("hrAppId"));
		//params.put("timestamp", Long.toString(System.currentTimeMillis()));
		//params.put("sign", SignKit.signSHA265(params, prop.getPropValue("hrKey")));
		return HttpXmlClient.post(url, params);
	}
	
	/**
	 * 格式化结果数据
	 * @param data
	 * @return
	 */
	protected JSONArray formatResultData(Object data){
		if(data==null)
			data = "";
		JSONObject json = JSON.parseObject(data.toString());
		if(StringKit.equals(json.getString("code"), "0")){
			return json.getJSONArray("result");
		}else{
			throw new RuntimeException(json.getString("msg"));
		}
	}
	
	/**
	 * 执行数据同步
	 * @return
	 */
	@Before(Tx.class)
	public SynResult executeSynData(){
		SynResult synResult = SynResult.me();
		try{
			Map<String,String> params = new HashMap<String,String>();
			initParams(params);
			Object resultObj = executeInterface(params);
			if( resultObj!=null ){
				JSONArray jsonArrData = formatResultData(resultObj);
				if(jsonArrData!=null){
					if(jsonArrData.size()>0){
						Result result = synMainData(jsonArrData);
						refreshCache();
						result = synpOtherData(result,jsonArrData);
						refreshCache();
						synResult.setResult(result);
					}else{
						throw new RuntimeException("接口返回0行数据！");
					}
				}else{
					throw new RuntimeException("接口返回非法数据，无法解析！");
				}
			}else{
				throw new RuntimeException("调用接口获取数据失败！");
			}
		}catch (Exception e) {
			LogKit.error("执行同步异常:",e);
			synResult.setResult(Result.me(e));
		}
		return synResult.end();
	}
	
	/**
	 * 同步主数据
	 * @param jsonArrData
	 * @return
	 */
	protected abstract Result synMainData(JSONArray jsonArrData);
	
	/**
	 * 同步扩展数据
	 * @param jsonArrData
	 * @return
	 */
	protected abstract Result synpOtherData(Result result,JSONArray jsonArrData);
	
	/**
	 * 刷新缓存数据
	 */
	protected abstract void refreshCache();

}
